package study.android.studyandroid.dao;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import study.android.LocalDb;
import tq.vmds.common.Util;
import tq.vmds.data.android.dto.TerminalInfo;
import tq.vmds.data.android.entity.ContactPhone;
import tq.vmds.data.android.entity.TerminalMaster;
import tq.vmds.data.android.entity.TqFence;
import tq.vmds.protocol.tq911.msg.param.KeyboardSetting;
import tq.vmds.protocol.tq911.msg.param.TrackTimesheet;
import tq.vmds.protocol.tq911.msg.param.WeeklyTimesheet;

public class DeviceDao extends BaseDao {
	public DeviceDao(LocalDb ldb) {
		super(ldb);
	}

	/**
	 * 保存终端详细资料，包括主从表。若原来已存在，则修改。
	 *
	 * @param ti
	 * @return
	 */
	public long saveTerminalInfo(TerminalInfo ti) {
		long rowId = saveTerminalMaster(ti);
		String serial = ti.getSerial();
		updateContactPhones(serial, 1, ti.getEmergencyPhones());
		updateAllTrackTimesheets(serial, ti.getTrackTimesheets());
		updateKbdSetting(serial, ti.getKbdSetting());
		updateAllFences(serial, ti.getFences());
		updateContactPhones(serial, 1, ti.getWhiteList());
		return rowId;
	}

	/**
	 *
	 * @param serial
	 * @param contactType
	 *            0:白名单；1:紧急号码
	 * @param contactPhones
	 */
	public void updateContactPhones(String serial, int contactType, List<ContactPhone> contactPhones) {
		db.execSQL("delete from contact_phone where serial=? and contactType=?", new Object[] { serial, contactType });
		List<String> rowIdList = new ArrayList<String>();
		for (ContactPhone entity : contactPhones) {
			ContentValues values = new ContentValues();
			values.put("serial", entity.getSerial());
			values.put("contactType", entity.getContactType());
			values.put("indexNo", entity.getIndexNo());
			values.put("contactPhoneId", Util.BigDecimal2str(entity.getContactPhoneId()));
			values.put("phoneNumber", entity.getPhoneNumber());
			values.put("contactName", entity.getContactName());
			long rowId = db.insert(LocalDb.table__contact_phone, null, values);
			rowIdList.add(Util.long2str(rowId));

		}
		Log.e("DAO", String.format("Insert contact_phone [%s]", Util.mergeStrings(rowIdList)));
	}

	public void updateAllTrackTimesheets(String serial, List<TrackTimesheet> trackTimesheets) {
		db.execSQL("delete from );
	}

	public void updateKbdSetting(String serial, KeyboardSetting kbdSetting) {
		// TODO Auto-generated method stub

	}

	public void updateAllFences(String serial, List<TqFence> fences) {
		db.execSQL("delete from tq_fence where serial=?", new Object[] { serial });
		List<String> rowIdList = new ArrayList<String>();
		for (TqFence entity : fences) {
			ContentValues values = new ContentValues();
			values.put("serial", entity.getSerial());
			values.put("fenceNo", entity.getFenceNo());
			values.put("fenceId", Util.BigDecimal2str(entity.getFenceId()));
			values.put("boundaryTypeCode", entity.getBoundaryTypeCode());
			values.put("minLat", entity.getMinLat());
			values.put("minLng", entity.getMinLng());
			values.put("maxLat", entity.getMaxLat());
			values.put("maxLng", entity.getMaxLng());
			values.put("alarmMode", entity.getAlarmMode());
			values.put("shapeData", entity.getShapeData());
			values.put("sendProgress", entity.getSendProgress());
			values.put("dyna_InstantInOut", entity.getDyna_InstantInOut());
			values.put("dyna_CalcValue", entity.getDyna_CalcValue());
			values.put("dyna_CalcInOut", entity.getDyna_CalcInOut());
			values.put("modifyTime", Util.datetime2str(entity.getModifyTime()));

			long rowId = db.insert(LocalDb.table__tq_fence, null, values);
			rowIdList.add(Util.long2str(rowId));
		}
		Log.e("DAO", String.format("Insert tq_fence [%s]", Util.mergeStrings(rowIdList)));
	}

	/**
	 * 保存终端详细资料，包括主从表。若原来已存在，则修改。
	 *
	 * @param tm
	 * @return
	 */
	public long saveTerminalMaster(TerminalMaster tm) {
		long rowId = 0;
		TerminalInfo tgi = this.fetchTerminalInfo(tm.getSerial());
		boolean exists = false;
		if (tgi != null) {
			exists = true;
			// this.deleteTerminalInfo(tm.getSerial());
		}

		ContentValues values = new ContentValues();
		values.put("serial", tm.getSerial());
		values.put("termRecId", Util.BigDecimal2str(tm.getTermRecId()));
		values.put("heartbeatInterval", tm.getHeartbeatInterval());
		// values.put("emergencyPhones", entity.getEmergencyPhones());
		// values.put("trackTimesheets",entity.getTrackTimesheets());
		// values.put("kbdSetting",entity.getKbdSetting());
		// values.put("whiteListEnabled",entity.getWhiteListEnabled());
		// values.put("fences",entity.getFences());
		values.put("tzOffset", tm.getTzOffset());
		values.put("fenceEnabled", tm.getFenceEnabled());
		values.put("serverHost", tm.getServerHost());
		values.put("serverIp", tm.getServerIp());
		values.put("serverPort", tm.getServerPort());
		// values.put("whiteList",entity.getWhiteList());
		values.put("workMode", tm.getWorkMode());
		values.put("weeklySelections", Util.Object2String(tm.getWeeklySelections()));
		values.put("authCode", tm.getAuthCode());
		values.put("statusMask", tm.getStatusMask());
		values.put("sensorMode", tm.getSensorMode());
		values.put("deviceTypeCode", tm.getDeviceTypeCode());
		values.put("carrierTypeID", tm.getCarrierTypeID());
		values.put("imei", tm.getImei());
		values.put("modifyTime", Util.datetime2str(tm.getModifyTime()));
		if (exists) {
			db.update(LocalDb.table__terminal_master, values, "serial=?", new String[] { tm.getSerial() });
		} else {
			rowId = db.insert(LocalDb.table__terminal_master, null, values);
		}
		return rowId;
	}

	public TerminalInfo fetchTerminalInfo(String serial) {
		TerminalInfo entity = null;
		String selectSql = String.format(defaultLocale,
				"SELECT " + //
						"serial, " + //
						"termRecId, " + //
						"heartbeatInterval, " + //
						// "emergencyPhones, " + //
						// "trackTimesheets, " + //
						// "kbdSetting, " + //
						// "whiteListEnabled, " + //
						// "fences, " + //
						"tzOffset, " + //
						"fenceEnabled, " + //
						"serverHost, " + //
						"serverIp, " + //
						"serverPort, " + //
						// "whiteList, " + //
						"workMode, " + //
						"weeklySelections, " + //
						"authCode, " + //
						"statusMask, " + //
						"sensorMode, " + //
						"deviceTypeCode, " + //
						"carrierTypeID, " + //
						"imei, " + //
						"modifyTime " + //
						"from terminal_master where serial='%s'",
				serial);
		Cursor cursor = db.rawQuery(selectSql, null);
		if (cursor.moveToNext()) {
			entity = new TerminalInfo();
			int colNo = 0;
			entity.setSerial(cursor.getString(colNo++));
			entity.setTermRecId(BigDecimal.valueOf(cursor.getLong(colNo++)));
			entity.setHeartbeatInterval(cursor.getInt(colNo++));
			entity.setTzOffset(cursor.getInt(colNo++));
			entity.setFenceEnabled(cursor.getInt(colNo++));
			entity.setServerHost(cursor.getString(colNo++));
			entity.setServerIp(cursor.getString(colNo++));
			entity.setServerPort(cursor.getInt(colNo++));
			entity.setWorkMode(cursor.getInt(colNo++));
			entity.weeklySelections(new WeeklyTimesheet(cursor.getString(colNo++)));
			entity.setAuthCode(cursor.getString(colNo++));
			entity.setStatusMask(cursor.getInt(colNo++));
			entity.setSensorMode(cursor.getInt(colNo++));
			entity.setDeviceTypeCode(cursor.getString(colNo++));
			entity.setCarrierTypeID(cursor.getInt(colNo++));
			entity.setImei(cursor.getString(colNo++));
			entity.setModifyTime(Util.date2Timestamp(Util.str2datetime(cursor.getString(colNo++))));
		}
		cursor.close();
		return entity;
	}

	/**
	 * 修改记录
	 */
	public int updateTerminalInfo(TerminalInfo entity) {
		ContentValues values = new ContentValues();
		// values.put("serial", entity.getSerial());
		values.put("termRecId", Util.BigDecimal2str(entity.getTermRecId()));
		values.put("heartbeatInterval", entity.getHeartbeatInterval());
		// values.put("emergencyPhones", entity.getEmergencyPhones());
		// values.put("trackTimesheets",entity.getTrackTimesheets());
		// values.put("kbdSetting",entity.getKbdSetting());
		// values.put("whiteListEnabled",entity.getWhiteListEnabled());
		// values.put("fences",entity.getFences());
		values.put("tzOffset", entity.getTzOffset());
		values.put("fenceEnabled", entity.getFenceEnabled());
		values.put("serverHost", entity.getServerHost());
		values.put("serverIp", entity.getServerIp());
		values.put("serverPort", entity.getServerPort());
		// values.put("whiteList",entity.getWhiteList());
		values.put("workMode", entity.getWorkMode());
		values.put("weeklySelections", entity.getWeeklySelections().toString());
		values.put("authCode", entity.getAuthCode());
		values.put("statusMask", entity.getStatusMask());
		values.put("sensorMode", entity.getSensorMode());
		values.put("deviceTypeCode", entity.getDeviceTypeCode());
		values.put("carrierTypeID", entity.getCarrierTypeID());
		values.put("imei", entity.getImei());
		values.put("modifyTime", Util.datetime2str(entity.getModifyTime()));

		String where = String.format(defaultLocale, "serial='%s'", entity.getSerial());
		int affectedRowNum = db.update("terminal_master", values, where, null);
		return affectedRowNum;
	}

	public void deleteTerminalInfo(String serial) {
		String sql = "DELETE FROM terminal_master WHERE serial=?";
		db.execSQL(sql, new Object[] { serial });
	}
}
